from flask import Flask, jsonify
from datetime import datetime
import sqlite3
import cPickle as pickle

app=Flask(__name__)

@app.route("/")
def index():
  return "PLACEHOLDER"

@app.route("/load_applications")
def load_applications():
  conn = sqlite3.connect("/Users/ebrynne/dev/hackday-01/src/hackday-01/hack.db")
  c = conn.cursor()
  apps = []
  scores = {}
  times = {}
  for row in c.execute("select * from applications;"):
    map = {}
    map['id'] = row[0]
    map['state'] = row[1]
    map['complete'] = row[2]
    map['start_time'] = row[3]
    map['states'] = pickle.loads(str(row[4]))
    map['scores'] = pickle.loads(str(row[5]))
    map['times'] = pickle.loads(str(row[6]))
    apps.append(map)

    for type, value in map['scores'].items():
      if type in scores:
        scores[type].append(value)
      else:
        scores[type] = [value]
    print scores

    for trans, time in map['times'].items():
      id1, id2 = trans.split("-")
      print id1
      print id2
      print times
      if id1 in times:
        if id2 in times[id1]:
          times[id1][id2].append(time)
        else:
          times[id1][id2] = [time]
      else:
        times[id1] = {}
        times[id1][id2] = []
        times[id1][id2].append(time)


  for key in times.keys():
      for key2 in times[key]:
        times[key][key2] = sum(times[key][key2])/len(times[key][key2])

  for key in scores.keys():
    scores[key] = sum(scores[key])/len(scores[key])

  return jsonify({"apps" : apps, "avg_scores" : scores,
                  "avg_times" : times})

if __name__ == '__main__':
  app.run(host='0.0.0.0', debug=True)